<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="../css/shoppingCar.css" />
    <script src="../js/jquery-3.6.0.min.js"></script>
    <script src="../js/interface.js"></script>
    <script src="../js/cookie.js"></script>
  </head>

  <body>
    <!-- 引入公共头部 -->
    <div class="header"></div>
    <script type="text/javascript">
      $(".header").load("common/head.html", function () {
        cookie = document.cookie;
        if (cookie) {
          username = getCookie("lgc");
          if (username) {
            $(".tipsBar").html(
              `<span>欢迎您,${username} | </span><span onclick="exit()">退出</span>`
            );
          } else {
            location.href =
              "login.html?returnUrl=" + encodeURIComponent(location.href);
          }
        }
      });
    </script>

    <!-- 购物车 -->
    <div class="pc_cart">
      <div class="cart">
        <div class="list-header">
          <div class="col col-check">
            <label>
              <input type="checkbox" class="check-all" />&emsp;全选
            </label>
          </div>
          <div class="col col-img"></div>
          <div class="col col-detail">商品名称</div>
          <div class="col col-price">单价</div>
          <div class="col col-count">购买数量</div>
          <div class="col col-subtotal">小计</div>
          <div class="col col-operate">操作</div>
        </div>
        <div class="list-body">
          <!-- <div class="list-item">
            <div class="col col-check">
              <label>
                <input type="checkbox" class="check-one" />
              </label>
            </div>
            <div class="col col-img">
              <img src="../images/x1622084912003_3600_x_448_x_448.jpg" alt="" />
            </div>
            <div class="col col-detail">红背心</div>
            <div class="col col-price">1599.00</div>
            <div class="col col-count">
              <div class="countBox">
                <span class="reduce">-</span>
                <span class="countSpan">1</span>
                <span class="add">+</span>
              </div>
            </div>
            <div class="col col-subtotal">1599.00</div>
            <div class="col col-operate">删除</div>
          </div> -->
        </div>
        <div class="list-footer">
          <div class="col col-continue">
            <a href="./goodsList.html">继续购物</a>
          </div>
          <div class="col col-pitch"><button>删除选中商品</button></div>
          <div class="col col-center">
            <div class="numTips">
              已选择 <span class="selectedNum">0</span> 件商品
            </div>
            <div class="priceTips">
              总计:<span class="selectedTotal">0</span>
            </div>
          </div>
          <div class="col col-total">
            <a href="">结算</a>
          </div>
        </div>
      </div>
    </div>

    <footer></footer>
    <script>
      $("footer").load(`common/footer.html`);
    </script>
  </body>
  <script>
    var cookie = document.cookie;
    var username = getCookie("lgc");
    var str = "";
    var sum;
    var allPrice;
    // console.log(username);
    function exit() {
      deleteCookie("lgc");
      location.reload();
    }
    $(document).on("click", ".searchBtn", function () {
      type = $(".searchCon").val();
      window.location.href = `./goodsList.html?type=${type}`;
    });
    $(async function () {
      //记录用户
      var result = await searchShoppingCarByUser({ username });
      // console.log(result);
      var status = result.status;
      var msg = result.msgl;
      var list = result.list;
      if (status) {
        var html = "";
        list.forEach(item => {
          var total = (parseInt(item.nowprice) * parseInt(item.buyNum)).toFixed(
            2
          );
          str += `<div class="list-item" data-id="${item.pid}">
                          <div class="col col-check">
                              <label>
                                  <input type="checkbox" class="check-one">
                              </label>
                          </div>
                          <div class="col col-img">
                              <img src="../${item.imgurl}"
                                  alt="">
                          </div>
                          <div class="col col-detail" title="${item.pname}">${item.pname}</div>
                          <div class="col col-price">${item.nowprice}</div>
                          <div class="col col-count">
                              <div class="countBox">
                                  <span class="reduce">-</span>
                                  <span class="countSpan">${item.buyNum}</span>
                                  <span class="add">+</span>
                              </div>
                          </div>
                          <div class="col col-subtotal">${total}</div>
                          <div class="col col-operate">删除</div>
                      </div>`;
        });
        $(".list-body").html(str);
      }
      // 全选:
      $(".check-all").click(function () {
        var status = $(this).prop("checked");
        $(".check-one").prop("checked", status);
        getTotal();
      });

      // 反选:
      $(".check-one").click(function () {
        isAllChecked();
        getTotal();
      });

      //+
      $(".add").click(function () {
        var num = $(this).prev().text();
        num++;
        $(this).prev().text(num);

        var price = $(this).parent().parent().prev().text();
        var subtotal = (price * num).toFixed(2);
        $(this).parent().parent().next().text(subtotal);
        $(this).prevAll(".reduce").text("-");

        var username = getCookie("lgc");
        var pid = $(this).parents(".list-item").attr("data-id");
        var buyNum = 1;
        addToShoppingCar({ username, pid, buyNum });
        getTotal();
      });

      // // 减：
      $(".reduce").click(function () {
        var num = $(this).next().text();
        if (num <= 1) return false;
        num--;
        if (num == 1) $(this).text("");
        $(this).next().text(num);
        var price = $(this).parent().parent().prev().text();
        var subtotal = (price * num).toFixed(2);
        $(this).parent().parent().next().text(subtotal);

        var username = getCookie("lgc");
        var pid = $(this).parents(".list-item").attr("data-id");
        var buyNum = -1;
        addToShoppingCar({ username, pid, buyNum });
        // getTotal();
      });

      // 单删:
      $(".col-operate").click(function () {
        if (confirm("是否删除选中商品？")) {
          $(this).parents(".list-item").remove();
          var pid = $(this).parents(".list-item").attr("data-id");
          deleteShopping({ username, pid });
        }
        isAllChecked();
        getTotal();
      });

      // // 删除选中
      $(".col-pitch").click(function () {
        if (confirm("是否删除全部选中商品?")) {
          Array.from($(".check-one")).forEach(item => {
            // console.log(item.parentNode.parentNode.parentNode);
            // console.log(item.checked);
            var res = item.parentNode.parentNode.parentNode;
            if (item.checked) {
              var pid = res.getAttribute("data-id");
              deleteShopping({ username, pid });
              res.remove();
            }
          });
        }
        isAllChecked();
        getTotal();
      });
      // 提交
      $(".col-total").click(function () {
        var plist = [];

        if (confirm("是否结算选中商品?")) {
          Array.from($(".check-one")).forEach(item => {
            var res = item.parentNode.parentNode.parentNode;
            if (item.checked) {
              var pid = res.getAttribute("data-id");
              plist.push(pid);
              // overShopping({ username, pid });
              // res.remove();
            }
          });
        }
        isAllChecked();
        getTotal();
        var pidlist = JSON.stringify(plist);
        // console.log(pidlist, allPrice, username, sum);
        addTolistcenter({ pidlist, allPrice, username, sum });
      });
      //判断全选
      function isAllChecked() {
        var flag = $(".check-one").is(":not(:checked)");
        $(".check-all").prop(
          "checked",
          $(".check-one").length == 0 ? false : !flag
        );
      }

      function getTotal() {
        sum = 0;
        allPrice = 0;
        $(".check-one:checked")
          .parents(".list-item")
          .each(function () {
            var num = $(this).find(".countSpan").text() * 1;
            var subtotal = $(this).find(".col-subtotal").text() * 1;
            // console.log(num, subtotal);
            sum += num;
            allPrice += subtotal;
          });

        $(".selectedNum").text(sum);
        $(".selectedTotal").text(allPrice.toFixed(2));
      }
    });

    function urlParse() {
      var search = location.search;
      var data = {};
      if (search) {
        var str = search.substring(1);
        console.log(str);
        var list = str.split("&");
        list.forEach(function (item) {
          var key = item.split("=")[0];
          var val = item.split("=")[1];
          data[key] = val;
        });
      }
      return data;
    }
  </script>
</html>
